using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WegasManagementSystem.BLL;
using WegasManagementSystem.Models;
using WegasManagementSystem.DAL;

namespace WegasManagementSystem.Forms
{
    public partial class AttendanceForm : Form
    {
        private readonly AttendanceBLL _attendanceBLL;
        private readonly EmployeeBLL _employeeBLL;
        private readonly DepartmentBLL _departmentBLL;
        private List<AttendanceInfo> _attendanceList;
        private int _currentYear;
        private int _currentMonth;

        public AttendanceForm()
        {
            InitializeComponent();
            _attendanceBLL = new AttendanceBLL();
            _employeeBLL = new EmployeeBLL();
            _departmentBLL = new DepartmentBLL();
            _currentYear = DateTime.Now.Year;
            _currentMonth = DateTime.Now.Month;
        }

        private void AttendanceForm_Load(object sender, EventArgs e)
        {
            try
            {
                // 初始化年月选择控件
                InitYearMonthPicker();
                
                // 加载部门树
                LoadDepartments();
                
                // 加载员工数据
                LoadEmployees();
                
                // 初始化界面
                InitUI();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载表单时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void InitYearMonthPicker()
        {
            // 设置年份选择器
            numYear.Minimum = 2000;
            numYear.Maximum = 2100;
            numYear.Value = _currentYear;

            // 设置月份选择器
            numMonth.Minimum = 1;
            numMonth.Maximum = 12;
            numMonth.Value = _currentMonth;
        }

        private void LoadDepartments()
        {
            try
            {
                // 获取部门列表
                var departments = _departmentBLL.GetAllDepartments();
                if (departments == null || !departments.Any())
                {
                    MessageBox.Show("没有找到部门数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 清空树节点
                treeDepartment.Nodes.Clear();

                // 添加根节点
                TreeNode rootNode = new TreeNode("全部部门");
                treeDepartment.Nodes.Add(rootNode);

                // 递归构建部门树
                BuildDepartmentTree(rootNode, departments, 0);

                // 展开根节点
                treeDepartment.ExpandAll();
                treeDepartment.SelectedNode = rootNode;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载部门数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BuildDepartmentTree(TreeNode parentNode, List<Department> departments, int parentId)
        {
            var children = departments.Where(d => d.ParentId == parentId).ToList();
            foreach (var dept in children)
            {
                TreeNode node = new TreeNode(dept.DeptName);
                node.Tag = dept;
                parentNode.Nodes.Add(node);

                // 递归添加子部门
                BuildDepartmentTree(node, departments, dept.DeptId);
            }
        }

        private void LoadEmployees(int? deptId = null)
        {
            try
            {
                List<Employee> employees;

                if (deptId.HasValue && deptId.Value > 0)
                {
                    // 获取指定部门的员工
                    employees = _employeeBLL.GetEmployeesByDepartment(deptId.Value);
                }
                else
                {
                    // 获取所有员工
                    employees = _employeeBLL.GetAllEmployees();
                }

                // 绑定到员工列表
                lstEmployees.Items.Clear();
                if (employees != null && employees.Any())
                {
                    foreach (var emp in employees)
                    {
                        ListViewItem item = new ListViewItem(emp.EmpNumber);
                        item.SubItems.Add(emp.Name);
                        item.SubItems.Add(emp.DeptName);
                        item.Tag = emp;
                        lstEmployees.Items.Add(item);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载员工数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void InitUI()
        {
            // 设置员工列表视图
            lstEmployees.View = View.Details;
            lstEmployees.FullRowSelect = true;
            lstEmployees.GridLines = true;
            
            if (lstEmployees.Columns.Count == 0)
            {
                lstEmployees.Columns.Add("工号", 100);
                lstEmployees.Columns.Add("姓名", 100);
                lstEmployees.Columns.Add("部门", 120);
            }

            // 设置考勤记录数据网格视图
            dataGridAttendance.AutoGenerateColumns = false;
            
            if (dataGridAttendance.Columns.Count == 0)
            {
                dataGridAttendance.Columns.Add("EmpNumber", "工号");
                dataGridAttendance.Columns["EmpNumber"].DataPropertyName = "EmpNumber";
                dataGridAttendance.Columns["EmpNumber"].Width = 80;
                
                dataGridAttendance.Columns.Add("EmpName", "姓名");
                dataGridAttendance.Columns["EmpName"].DataPropertyName = "EmpName";
                dataGridAttendance.Columns["EmpName"].Width = 80;
                
                dataGridAttendance.Columns.Add("DeptName", "部门");
                dataGridAttendance.Columns["DeptName"].DataPropertyName = "DeptName";
                dataGridAttendance.Columns["DeptName"].Width = 120;
                
                dataGridAttendance.Columns.Add("Year", "年份");
                dataGridAttendance.Columns["Year"].DataPropertyName = "Year";
                dataGridAttendance.Columns["Year"].Width = 60;
                
                dataGridAttendance.Columns.Add("Month", "月份");
                dataGridAttendance.Columns["Month"].DataPropertyName = "Month";
                dataGridAttendance.Columns["Month"].Width = 60;
                
                dataGridAttendance.Columns.Add("WorkDays", "应出勤天数");
                dataGridAttendance.Columns["WorkDays"].DataPropertyName = "WorkDays";
                dataGridAttendance.Columns["WorkDays"].Width = 100;
                
                dataGridAttendance.Columns.Add("ActualWorkDays", "实际出勤天数");
                dataGridAttendance.Columns["ActualWorkDays"].DataPropertyName = "ActualWorkDays";
                dataGridAttendance.Columns["ActualWorkDays"].Width = 100;
                
                dataGridAttendance.Columns.Add("AbsenceDays", "缺勤天数");
                dataGridAttendance.Columns["AbsenceDays"].DataPropertyName = "AbsenceDays";
                dataGridAttendance.Columns["AbsenceDays"].Width = 80;
                
                dataGridAttendance.Columns.Add("OvertimeHours", "加班小时数");
                dataGridAttendance.Columns["OvertimeHours"].DataPropertyName = "OvertimeHours";
                dataGridAttendance.Columns["OvertimeHours"].Width = 100;
                
                dataGridAttendance.Columns.Add("LateCount", "迟到次数");
                dataGridAttendance.Columns["LateCount"].DataPropertyName = "LateCount";
                dataGridAttendance.Columns["LateCount"].Width = 80;
                
                dataGridAttendance.Columns.Add("EarlyLeaveCount", "早退次数");
                dataGridAttendance.Columns["EarlyLeaveCount"].DataPropertyName = "EarlyLeaveCount";
                dataGridAttendance.Columns["EarlyLeaveCount"].Width = 80;
            }

            // 初始查询部门下的考勤记录
            QueryAttendance();
        }

        /// <summary>
        /// 查询考勤记录
        /// </summary>
        private void QueryAttendance()
        {
            try
            {
                // 获取当前选中的年月
                int year = (int)numYear.Value;
                int month = (int)numMonth.Value;

                // 检查是否选中了部门
                if (treeDepartment.SelectedNode != null && treeDepartment.SelectedNode.Tag is Department dept)
                {
                    // 查询选中部门的考勤记录
                    _attendanceList = _attendanceBLL.GetAttendanceByDepartment(dept.DeptId, year, month);
                }
                else
                {
                    // 查询所有考勤记录
                    _attendanceList = _attendanceBLL.GetAllAttendancesByYearMonth(year, month);
                }

                // 显示查询结果
                dataGridAttendance.DataSource = _attendanceList;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询考勤记录时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            QueryAttendance();
        }

        private void numYear_ValueChanged(object sender, EventArgs e)
        {
            _currentYear = (int)numYear.Value;
        }

        private void numMonth_ValueChanged(object sender, EventArgs e)
        {
            _currentMonth = (int)numMonth.Value;
        }

        private void treeDepartment_AfterSelect(object sender, TreeViewEventArgs e)
        {
            // 选择部门后，加载该部门下的员工
            if (e.Node != null)
            {
                if (e.Node.Tag is Department dept)
                {
                    LoadEmployees(dept.DeptId);
                }
                else
                {
                    // 选中的是根节点
                    LoadEmployees();
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            // 检查是否选中了员工
            if (lstEmployees.SelectedItems.Count == 0)
            {
                MessageBox.Show("请先选择员工", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var employee = lstEmployees.SelectedItems[0].Tag as Employee;
            if (employee == null)
            {
                MessageBox.Show("获取员工信息失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            int year = (int)numYear.Value;
            int month = (int)numMonth.Value;

            try
            {
                // 检查是否已存在该员工当月的考勤记录
                var existingAttendance = _attendanceBLL.GetAttendanceByEmployee(employee.EmpId, year, month);
                if (existingAttendance != null)
                {
                    MessageBox.Show($"{employee.Name} 在 {year}年{month}月 的考勤记录已存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 显示考勤信息编辑对话框
                using (AttendanceEditForm editForm = new AttendanceEditForm())
                {
                    // 创建新的考勤信息
                    AttendanceInfo attendance = new AttendanceInfo
                    {
                        EmpId = employee.EmpId,
                        EmpName = employee.Name,
                        DeptId = employee.DeptId,
                        DeptName = employee.DeptName,
                        Year = year,
                        Month = month,
                        WorkDays = 21.75m, // 默认工作日
                        ActualWorkDays = 21.75m,
                        AbsenceDays = 0,
                        OvertimeHours = 0,
                        LateCount = 0,
                        EarlyLeaveCount = 0
                    };

                    editForm.AttendanceInfo = attendance;
                    editForm.IsAdd = true;

                    if (editForm.ShowDialog() == DialogResult.OK)
                    {
                        // 添加考勤记录
                        int newId = _attendanceBLL.AddAttendance(editForm.AttendanceInfo);
                        if (newId > 0)
                        {
                            MessageBox.Show("添加考勤记录成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            
                            // 刷新考勤记录
                            QueryAttendance();
                        }
                        else
                        {
                            MessageBox.Show("添加考勤记录失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加考勤记录时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dataGridAttendance.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择要编辑的考勤记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var selectedIndex = dataGridAttendance.SelectedRows[0].Index;
            if (selectedIndex < 0 || selectedIndex >= _attendanceList.Count)
            {
                MessageBox.Show("获取考勤记录失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var attendance = _attendanceList[selectedIndex];

            try
            {
                // 显示考勤信息编辑对话框
                using (AttendanceEditForm editForm = new AttendanceEditForm())
                {
                    editForm.AttendanceInfo = attendance;
                    editForm.IsAdd = false;

                    if (editForm.ShowDialog() == DialogResult.OK)
                    {
                        // 更新考勤记录
                        bool success = _attendanceBLL.UpdateAttendance(editForm.AttendanceInfo);
                        if (success)
                        {
                            MessageBox.Show("更新考勤记录成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            
                            // 刷新考勤记录
                            QueryAttendance();
                        }
                        else
                        {
                            MessageBox.Show("更新考勤记录失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"编辑考勤记录时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dataGridAttendance.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择要删除的考勤记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var selectedIndex = dataGridAttendance.SelectedRows[0].Index;
            if (selectedIndex < 0 || selectedIndex >= _attendanceList.Count)
            {
                MessageBox.Show("获取考勤记录失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var attendance = _attendanceList[selectedIndex];

            try
            {
                // 确认删除
                DialogResult result = MessageBox.Show(
                    $"确定要删除 {attendance.EmpName} 在 {attendance.Year}年{attendance.Month}月 的考勤记录吗？",
                    "确认删除",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    // 执行删除
                    bool success = _attendanceBLL.DeleteAttendance(attendance.AttendanceId);
                    if (success)
                    {
                        MessageBox.Show("删除考勤记录成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        
                        // 刷新考勤记录
                        QueryAttendance();
                    }
                    else
                    {
                        MessageBox.Show("删除考勤记录失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除考勤记录时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 导入考勤记录按钮点击事件
        /// </summary>
        private void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog openDialog = new OpenFileDialog();
                openDialog.Filter = "Excel文件(*.xlsx)|*.xlsx|Excel 2003文件(*.xls)|*.xls|CSV文件(*.csv)|*.csv|所有文件(*.*)|*.*";
                openDialog.FilterIndex = 1;
                openDialog.RestoreDirectory = true;
                openDialog.Title = "请选择要导入的考勤数据文件";

                if (openDialog.ShowDialog() == DialogResult.OK)
                {
                    string filePath = openDialog.FileName;
                    
                    // 显示导入进度对话框
                    using (ImportProgressForm progressForm = new ImportProgressForm())
                    {
                        progressForm.StartPosition = FormStartPosition.CenterParent;
                        progressForm.Show(this);
                        progressForm.SetStatus("正在导入考勤数据...");
                        
                        // 执行导入操作
                        int importCount = _attendanceBLL.ImportAttendanceFromExcel(filePath);
                        
                        // 关闭进度对话框
                        progressForm.Close();
                        
                        if (importCount > 0)
                        {
                            MessageBox.Show($"成功导入 {importCount} 条考勤记录！", "导入成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            
                            // 刷新考勤记录
                            QueryAttendance();
                        }
                        else
                        {
                            MessageBox.Show("没有导入任何考勤记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导入考勤记录时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 导出考勤记录按钮点击事件
        /// </summary>
        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取当前查询条件
                int year = (int)numYear.Value;
                int month = (int)numMonth.Value;
                
                // 获取选中的部门ID
                int deptId = 0; // 默认导出所有部门
                if (treeDepartment.SelectedNode != null && treeDepartment.SelectedNode.Tag != null)
                {
                    deptId = (int)treeDepartment.SelectedNode.Tag;
                }
                
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.Filter = "Excel文件(*.xlsx)|*.xlsx|Excel 2003文件(*.xls)|*.xls|CSV文件(*.csv)|*.csv";
                saveDialog.FilterIndex = 1;
                saveDialog.RestoreDirectory = true;
                saveDialog.Title = "请选择导出文件保存位置";
                saveDialog.FileName = $"考勤记录_{year}年{month:D2}月";
                
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    string filePath = saveDialog.FileName;
                    
                    // 显示导出进度对话框
                    using (ExportProgressForm progressForm = new ExportProgressForm())
                    {
                        progressForm.StartPosition = FormStartPosition.CenterParent;
                        progressForm.Show(this);
                        progressForm.SetStatus("正在导出考勤数据...");
                        
                        // 执行导出操作
                        bool success = _attendanceBLL.ExportAttendanceToExcel(deptId, year, month, filePath);
                        
                        // 关闭进度对话框
                        progressForm.Close();
                        
                        if (success)
                        {
                            MessageBox.Show("考勤记录导出成功！", "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            MessageBox.Show("考勤记录导出失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出考勤记录时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void lstEmployees_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (lstEmployees.SelectedItems.Count > 0)
                {
                    // 获取选中的员工
                    var employee = lstEmployees.SelectedItems[0].Tag as Employee;
                    if (employee != null)
                    {
                        int year = (int)numYear.Value;
                        int month = (int)numMonth.Value;

                        // 根据选中的员工查询考勤记录
                        var attendance = _attendanceBLL.GetAttendanceByEmployee(employee.EmpId, year, month);
                        // 重置列表
                        _attendanceList = new List<AttendanceInfo>();
                        // 如果查询到结果，则添加到列表中
                        if (attendance != null)
                        {
                            _attendanceList.Add(attendance);
                        }
                        // 更新数据源
                        dataGridAttendance.DataSource = _attendanceList;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询员工考勤记录时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
} 